package com.fecean.aabbc.commons.validator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author Zhengjingfeng
 * @created 2019/4/28 9:15
 * @comment 属性校验工具类
 */
@SuppressWarnings("all")
public abstract class ValidationUtil {

    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 对参数校验对象使用指定的校验组进行校验
     *
     * @param obj    参数校验对象
     * @param groups 校验组
     * @return
     */
    public static <T> ValidationResult validateEntity(T obj, Class<?>... groups) {
        Objects.requireNonNull(obj, "参数校验对象不能为空");
        ValidationResult result = new ValidationResult();
        Set<ConstraintViolation<T>> set = validator.validate(obj, groups);
        if (set != null && !set.isEmpty()) {
            result.setHasErrors(true);
            Map<String, String> errorMsg = new HashMap<>(obj.getClass().getDeclaredFields().length);
            for (ConstraintViolation<T> cv : set) {
                errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());
            }
            result.setErrorMsg(errorMsg);
        }
        return result;
    }

    /**
     * 对参数校验对象的指定参数使用指定的校验组进行校验
     *
     * @param obj          参数校验对象
     * @param propertyName 参数名
     * @param groups       校验组
     * @return
     */
    public static <T> ValidationResult validateProperty(T obj, String propertyName, Class<?>... groups) {
        Objects.requireNonNull(obj, "参数校验对象不能为空");
        ValidationResult result = new ValidationResult();
        Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, groups);
        if (set != null && !set.isEmpty()) {
            result.setHasErrors(true);
            Map<String, String> errorMsg = new HashMap<>(obj.getClass().getDeclaredFields().length);
            for (ConstraintViolation<T> cv : set) {
                errorMsg.put(propertyName, cv.getMessage());
            }
            result.setErrorMsg(errorMsg);
        }
        return result;
    }
}
